package com.sq.partner.manager.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.sso.filter.SSOFilter;
import com.sq.partner.manager.util.LogUtil;

/**
 * Servlet Filter implementation class GatewayManagerFilter
 */
public class ManagerAuthorityFilter implements Filter {
	private static Logger logger = LogUtil.getLog(ManagerAuthorityFilter.class);
	private  List<Pattern> noCheckPatterns = new ArrayList<Pattern>();

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 权限验证
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		String uri = req.getRequestURI();
		String path = req.getContextPath();
		String uriNoPath = uri.replaceFirst(path, "");
		if(uriNoPath.indexOf(";") != -1){
			uriNoPath = uriNoPath.substring(0,uriNoPath.indexOf(";"));
		}
		boolean checkUri= checkUri(req,uriNoPath);
		if(checkUri){
			chain.doFilter(request, response);
		}else{
			String msg = "当前用户没有操作["+uriNoPath+"]执行权限";
			req.setAttribute("dispatchUri", "/common/error");
            SSOFilter.doLoginError(req, res, msg);
			
		}
			
	}
	/**
	 * 判断用户是否有操作权限
	 */
	private boolean checkUri(HttpServletRequest request,String uriNoPath){

		HttpSession session = request.getSession();
		GatewayUser user = null;
		List<String> uris=null;
		//公共操作
		if(!noCheckPatterns.isEmpty()){
			for(Pattern p : noCheckPatterns){
				if(p.matcher(uriNoPath).matches()){
					return true;
				}
			}
		}
		
		//非公共逻辑 初使数据
		List<Pattern> checkPatterns = (List)session.getAttribute(Constants.SESSION_CHECK_PATTERN);
		Long patternUser = (Long)session.getAttribute("pattern_user");
		user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		if(user == null){//用户为空 不验证登陆逻辑
			return true;
		}
		
		if(checkPatterns == null || !user.getUserid().equals(patternUser)){
			
			uris = user.getUriList();
			//将uris转化为正则表达式 主要是对 *的转换
			if(uris != null && !uris.isEmpty()){
				checkPatterns = new ArrayList<Pattern>();
				for(String s : uris){
					checkPatterns.add(SSOFilter.str2Pattern(s));
				}
				session.setAttribute(Constants.SESSION_CHECK_PATTERN, checkPatterns);
				session.setAttribute("pattern_user", user.getUserid());
			}
		}
		//判断前页面访问url 是否为值 否则查找用户权限列表
		String deptUri = (String)session.getAttribute(Constants.DEPT_URI);
		if(deptUri != null && deptUri.equals(uriNoPath)){
			return true;
		}
		
		//权限判断
		if(checkPatterns != null && !checkPatterns.isEmpty()){
			for(Pattern p : checkPatterns){
				if(p.matcher(uriNoPath).matches()){
					session.setAttribute(Constants.DEPT_URI, uriNoPath);
					return true;
				}
			}
		}
		
		return false;
	}
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String noCheckPath = fConfig.getInitParameter("noCheckPath");
		logger.info("不验证权限路径:\n"+noCheckPath);
		if(noCheckPath != null){
			String[] noCheckArray = noCheckPath.split(",");
			for(String s : noCheckArray){
				noCheckPatterns.add(SSOFilter.str2Pattern(s));
			}
		}
	}
}
